//
//  TimeRecordStore.swift
//  CrseAsst
//
//  Created by 申铭 on 2024/2/27.
//

import Foundation
import CoreData

enum TimeRecordType: Int {
    case s
}

class TimeRecordStore {
    
    static func save(_ record: TimeRecord) {
        do {
            try kStoreContext.save()
        } catch {
            log.error("保存错误：\(error)")
        }
    }
    
    static func query(groupId: String) -> [TimeRecord] {
        let fetchRequest = NSFetchRequest<TimeRecord>(entityName: EntityName.timeRecord)
        let predicate = NSPredicate(format: "groupId == %@", groupId)
        fetchRequest.predicate = predicate
        fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \TimeRecord.createTime, ascending: false)]
        
        do {
            let arr = try kStoreContext.fetch(fetchRequest)
            for a in arr {
                log.verbose(a.title ?? "无")
            }
            return arr
        } catch {
            log.error("查询错误：\(error)")
        }
        
        return [TimeRecord]()
    }
    
    /// 记录耗时
    /// - Parameters:
    ///   - duration: 持续时间
    ///   - type: 类型
    static func record(uuid: String, duration: TimeInterval, timer: CATimer) {
        if let statistics = find(uuid: uuid) { // 有，改
            statistics.duration = duration
        } else {
            guard let record = NSEntityDescription.insertNewObject(forEntityName: EntityName.timeRecord, into: kStoreContext) as? TimeRecord else {
                log.error("TimeRecord对象转换失败")
                return
            }
            
            let now = Date().timeIntervalSince1970
            record.uuid = uuid
            record.duration = duration
//            record.type = Int32(type.rawValue)
            record.timer = timer
            record.createTime = now
            record.updateTime = now
        }
        
        do {
            try kStoreContext.save()
        } catch {
            log.error("保存错误：\(error)")
        }
    }
    
    static func find(uuid: String) -> TimeRecord? {
        let fetchRequest = NSFetchRequest<TimeRecord>(entityName: EntityName.timeRecord)
        let predicate = NSPredicate(format: "uuid == %@", uuid) // 设置查询条件
        fetchRequest.predicate = predicate

        do {
            let fetchedObjects = try kStoreContext.fetch(fetchRequest)
            return fetchedObjects.first
        } catch {
            log.error("查询错误：\(error)")
        }
        
        return nil
    }
    
}
